import axios from 'axios';
import qs from 'qs';
import { Toast } from 'mint-ui';

/**
 *  状态码
 */
const CODE = {
	SUCCESS: 0,
	ERROR: 400,
	FAIL: -1
};

export default {
	install( Vue, options ) {
		Vue.prototype.httpGet = ( url, params = {} ) => {
			url = window.baseURL + url;
			return axios.get( url, {
					params: params
				} )
				.then( function ( res ) {
					if ( res.data && res.data.code === CODE.SUCCESS ) {
						return res.data;
					}
					if ( res.data && res.data.code === CODE.ERROR ) {
						return Promise.reject( res.data.error );
					}
					if ( res.data && res.data.code === CODE.FAIL ) {
						Toast( {
							message: res.data.msg,
							duration: 2000
						} )
						return Promise.reject( res.data.error );
					}
				} )
				.catch( function ( error ) {
					console.log( error );
				} )
		};

		Vue.prototype.httpPost = ( url, params = {} ) => {
			url = window.baseURL + url;
			return axios.post( url, params )
				.then( function ( res ) {
					// console.log(res);
					if ( res.data && res.data.code === CODE.SUCCESS ) {
						return res.data;
					}
					if ( res.data && res.data.code === CODE.ERROR ) {
						return Promise.reject( res.data.error );
					}
					if ( res.data && res.data.code === CODE.FAIL ) {
						Toast( {
							message: res.data.msg,
							duration: 2000
						} )
						// return Promise.reject(res.data.msg);
					}
				} )
				.catch( function ( error ) {
					console.log( error );
				} )
		};

		Vue.prototype.httpPost2 = ( url, params = {} ) => {
			return axios.post( url, params )
				.then( function ( res ) {
					console.log( res );
					if ( res.data && res.data.status === 'success' ) {
						Toast( {
							message: res.data.message,
							duration: 2000
						} )
						//return res.data;
					}
					if ( res.data && res.data.status === 'error' ) {
						Toast( {
							message: res.data.message,
							duration: 2000
						} )
						// return Promise.reject(res.data.msg);
					}
				} )
				.catch( function ( error ) {
					console.log( error );
				} )
		};

		Vue.prototype.httpDelete = ( url, params = {} ) => {
			return axios( {
					method: 'DELETE',
					url: url,
					data: params
				} ).then( function ( res ) {
					console.log( res )
					if ( res.data && res.data.code === CODE.SUCCESS ) {
						return res.data;
					}
					if ( res.data && res.data.code === CODE.ERROR ) {
						Toast( {
							message: res.data.error,
							duration: 2000
						} )
						return Promise.reject( res.data.error )
					}
				} )
				.catch( function ( error ) {
					console.log( error )
				} )
		};
	}
}